# -*- coding: utf-8 -*-
import oss2
import os
import sys
import json
import copy
import codecs
import subprocess
from collections import OrderedDict

curPath = os.path.split(sys.argv[0])[0]
uploadConfigPath = os.path.join(curPath, "projectConfig.json")

projectName = sys.argv[1]  # 游戏工程名
platform = sys.argv[2]  # Android or IOS
remoteBundleDirKey = sys.argv[3]  # debug or release

localGameInfoPath = None  # 本地GameInfo存储路径
ossConfig = None  # oss配置信息


def get_upload_config():
    with open(uploadConfigPath) as c:
        cf = json.load(c)
        global localGameInfoPath
        global ossConfig
        localGameInfoPath = cf[projectName]["LocalGameInfoPath"]
        ossConfig = cf[projectName]["OssConfig"]
        return cf[projectName]["BundleConfig"]


uploadConfig = get_upload_config()
pathFile = uploadConfig["SourcePath"][platform]  # 本地bundle存储路径
ossDir = uploadConfig["OssDir"][remoteBundleDirKey]  # Bundle上传路径
ossKey = ossConfig["ossKey"]  # ossKey
ossPassword = ossConfig["ossPassword"]  # ossPassword
ossBucket = ossConfig["ossBucket"]  # oss仓库名称
ossNode = None
try:
    ossNode = ossConfig["ossNode"]  # oss仓库节点
except Exception as e:
    ossNode = None

cmd1 = r"cd C:\Program Files\TortoiseSVN\bin"
cmd2 = r'svn.exe update %s --non-interactive --trust-server-cert-failures="unknown-ca,cn-mismatch,expired,not-yet-valid,other" --username Build --password zhanlong888' % pathFile
cmd3 = 'cd %s' % pathFile
cmd = cmd1 + " && " + cmd2 + " && " + cmd3
subprocess.call(cmd, shell=True)

# 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
auth = oss2.Auth(ossKey, ossPassword)
# Endpoint以杭州为例，其它Region请按实际情况填写。http://resourcesdate.oss-cn-hangzhou.aliyuncs.com/ai_head/10249.jpg
if None == ossNode:
    ossNode = "http://oss-cn-hangzhou.aliyuncs.com"
bucket = oss2.Bucket(auth, ossNode, ossBucket)

# <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
# <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
# result = bucket.put_object_from_file('game/release/123.txt', 'D:/123.txt')
# print(result.status)


failedNames = []


# 定义是目录
def list(dir):
    fs = os.listdir(dir)
    for f in fs:
        file = dir + "/" + f;
        if os.path.isdir(file):
            list(file)
        else:
            uploadDir(file)


# 上传带目录的文件到OSS
def uploadDir(path_filename):
    remoteName = ossDir + path_filename.split('//')[1]
    result = bucket.put_object_from_file(remoteName, path_filename)
    if result.status == 203:
        failedNames.append(path_filename)


# 上传文件到OSS
def uploadFile(filename):
    remoteName = ossDir + os.path.basename(filename)
    result = bucket.put_object_from_file(remoteName, filename)
    if result.status == 203:
        failedNames.append(filename)


gameVersion = ""
file_new = ""
lists = os.listdir(pathFile)  # 列出目录的下所有文件和文件夹保存到lists
lists.(key=lambda fn: os.path.getmtime(pathFile + "/" + fn))  # 按时间排序
for i in range(len(lists) - 1, -1, -1):
    if lists[i].endswith(".apk") or lists[i].endswith(".ipa"):
        continue
    file_new = os.path.join(pathFile, lists[i])
    gameVersion = lists[i]
    break

print(gameVersion)

file_new_status = None  # 将上传操作放到最后，优先修改GameInfo.txt 防止上传失败导致GameInfo.txt未被修改到

# 判断是文件还是目录
if os.path.isdir(file_new):
    if file_new == "":
        print("路径为空,程序终止")
        sys.exit()
    if file_new.endswith('/'):
        pass
    else:
        file_new += "/"
    # list(file_new)
    file_new_status = 1
elif os.path.isfile(file_new):
    file_new_status = 2
    # uploadFile(file_new)
else:
    print("it's a special file (socket, FIFO, device file)")


# 修改GameInfo.txt相关游戏的版本内容
def update_game_info_version(gameName):
    with open(localGameInfoPath, 'r', encoding='utf-8') as file_open:
        data = json.load(file_open,object_pairs_hook=OrderedDict)
        for line in data:
            if line['name'] in gameName:
                if platform == "IOS":
                    line['iosversion'] = gameVersion
                    line['iostestVersion'] = gameVersion
                if platform == "Android":
                    line['androidtestVersion'] = gameVersion
                    line['androidversion'] = gameVersion
    with open(localGameInfoPath, 'wb') as f:
        json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False, indent=4)


# 开始执行修改GameInfo.txt
def update_game_info():
    gameNames = []
    global platform
    for root, dirs, files in os.walk(file_new):
        if root.endswith("Android"):
            gameNames[:] = copy.deepcopy(dirs)
            platform = "Android"
            break
        if root.endswith("IOS"):
            platform = "IOS"
            gameNames[:] = copy.deepcopy(dirs)
            break
    update_game_info_version(gameNames)

if remoteBundleDirKey == "debug":
    updateGameInfoCmd = r'svn.exe update %s --non-interactive --trust-server-cert-failures="unknown-ca,cn-mismatch,expired,not-yet-valid,other" --username Build --password zhanlong888' % localGameInfoPath
    subprocess.call(updateGameInfoCmd, shell=True)
    update_game_info()
    # 上传最新的GameInfo.txt到svn
    commitGameInfoCmd = r'svn commit %s -m "Update %s GameInfo" --non-interactive --trust-server-cert-failures="unknown-ca,cn-mismatch,expired,not-yet-valid,other" --username Build --password zhanlong888' % (localGameInfoPath,platform)
    subprocess.call(commitGameInfoCmd, shell=True)

# 根据待上传文件类型执行对应方法  1：目录  2：文件
if file_new_status == 1:
    list(file_new)
elif file_new_status == 2:
    uploadFile(file_new)

if len(failedNames) > 0:
    for str in failedNames:
        print(str)
print("上传完成,上传失败个数为: ", len(failedNames))
